import {
  CaretRightOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
  CloseOutlined,
  DeliveredProcedureOutlined,
  EyeInvisibleOutlined,
  ClockCircleOutlined,
  FileProtectOutlined,
} from '@ant-design/icons';
import { Drawer, Descriptions, Row, Col, Button, Timeline, Spin, Collapse, Divider, Space, Form, Select, Input, message, Image, Empty } from 'antd';
import { signStateOfRenderings } from '../common';
import { MaterialManageAPI } from '../common/type';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import React, { useState, useEffect, useCallback } from 'react';
import MyIcon from '@/components/MyIcon';
import '../common/styles.less';
import pageStyles from '@/common/pageLayout.less';
import { auditMaterialServices, detailMaterialServices } from '../services';
import ApplySignModal from './SignModalDrawer';
import { formatDecimal, getColorTextDoms } from '../../Acommon';
import { getBaseUrl } from '@/services/urlconst';
const { Panel } = Collapse;
const getKey = () => String(Math.random() * 1000000) + '-' + String(Math.random() * 1000000);
const activeKeys = ['material-Collapse', 'material-CollapseCheck'];
/**
 * 详情
 * @param onClose  关闭方法
 * @param isShowDetail  isShow
 * @param recordObj  点击对象
 */
const DetailsDrawer: React.FC<MaterialManageAPI.DetailsDrawerAPI> = ({ onClose, isShowDetail, recordObj, curRes, reloadManage }) => {
  let reqUrl = getBaseUrl();

  /**表单的ref*/
  const [auditForm] = Form.useForm(); //表单 form

  /**本组件展示数据的对象*/
  const [record, setRecord] = useState<Record<string, any>>({});

  /**发布，申请弹窗*/
  const [isShowApplyModal, setIsShowApplyModal] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
    type: null,
    select: null,
  });

  /**Spin*/
  const [isSpin, setIsSpin] = useState(false);

  /**audit*/
  const [isAudit, setIsAudit] = useState(false);

  /**样式*/
  const prefixCls = 'material-updata-';

  const [imgArr, setImgArr] = useState([]);

  /**文本框*/
  const [isChange, setIsChange] = useState<boolean>(false);

  const [activeKey, setActiveKey] = useState<Array<string>>(activeKeys);

  /**是否展示放大图片-眼睛状态*/
  const [isShowEye, setIsShowEye] = useState<boolean>(false);

  /**改变eye状态方法*/
  const handleClickEye = () => {
    setIsShowEye(!isShowEye);
  };

  /**抽屉详情的关闭方法**/
  const oneDetailClose = () => {
    setIsAudit(false);
    onClose();
  };

  /**详情方法Callback*/
  const detailMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      /**保存一份数据*/
      setRecord(res?.obj);
      message.success(res?.msg);
      if (res?.obj?.imageInfo) {
        let imgList = res?.obj?.imageInfo?.split('||');
        setImgArr(imgList);
      }
    }
  };

  /**审核方法Callback*/
  const auditMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      auditForm?.resetFields();
      setIsAudit(false);
      // 调详情接口
      detailMaterialRun({ id: record?.id });
      reloadManage();
    }
  };

  /**详情方法services*/
  const { detailMaterialRun, detailMaterialLoading } = detailMaterialServices(detailMaterialCallback);

  /**审核方法services*/
  const { auditMaterialRun, auditMaterialLoading } = auditMaterialServices(auditMaterialCallback);

  /**获取img集合*/
  useEffect(() => {
    /**获取详情*/
    if (recordObj?.id) {
      detailMaterialRun({ id: recordObj?.id });
    }
  }, [recordObj?.id]);

  useEffect(() => {
    if (isShowDetail) {
      setIsSpin(true);
      setTimeout(() => {
        setIsSpin(false);
      }, 800);
    }
  }, [isShowDetail]);

  /**抽屉title全展按钮**/
  const extraRender = () => (
    <Space>
      <Button
        type={!activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleLeftOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allClose');
        }}
        disabled={!activeKey.length ? true : false}
      >
        全部折叠
      </Button>
      <Button
        type={activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleRightOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allOpen');
        }}
        disabled={activeKey.length == 3 ? true : false}
      >
        全部展开
      </Button>
    </Space>
  );

  /**
   * @collAllRemove
   * @description 折叠面板全选于反选
   * @param clickType 类型
   */
  const collAllRemove = (clickType: string) => {
    if (clickType == 'allOpen') {
      changeCollKey(activeKeys);
    }
    if (clickType == 'allClose') {
      changeCollKey([]);
    }
  };

  const changeCollKey = useCallback(
    (keyList: string[]) => {
      setActiveKey(keyList);
    },
    [activeKey],
  );

  /**
   * @onChangeActivekey
   * @description 折叠面板操作
   * @param keys 面板的 keys
   */
  const onChangeActivekey = (keys: string | string[]) => {
    setActiveKey(Array.isArray(keys) ? keys : [keys]);
  };

  return (
    <>
      <Drawer
        className={prefixCls + 'MaterialDetailDrawer'}
        title="物料详情"
        style={{ position: 'absolute', height: '100%', overflow: 'hidden' }}
        placement="right"
        onClose={oneDetailClose}
        open={isShowDetail}
        getContainer={false}
        width={document.body?.clientWidth * 0.45}
        headerStyle={{ padding: '1rem' }}
        bodyStyle={{ padding: 0 }}
        closable={false}
        destroyOnClose={true}
        extra={extraRender()}
      >
        <div
          id="oneDetailDrawerBox"
          className={isAudit ? prefixCls + 'strutDetailDrawerBox' : prefixCls + 'allDetailDrawerBox'}
          style={{
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
          }}
        >
          <ScrollBarLayout style={{ padding: '5px 0px', flex: 'auto' }}>
            <Spin spinning={isSpin || detailMaterialLoading}>
              {/* 基本信息 */}
              <Collapse
                bordered={false}
                className={prefixCls + 'updateCollapse'}
                expandIconPosition="end"
                activeKey={activeKey}
                onChange={onChangeActivekey}
                expandIcon={({ isActive }) => {
                  return <CaretRightOutlined rotate={isActive ? 90 : 0} />;
                }}
              >
                {/* 基本信息 */}
                <Panel header={<Divider orientation="left">{'基本信息'}</Divider>} key={'material-Collapse'} id={'material-Collapse'}>
                  <div className={prefixCls + 'Descriptions'} style={{ margin: '0 10px' }}>
                    <Descriptions bordered={true} size="small" column={2} labelStyle={{ width: 80 }}>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-barcode'} />
                            &nbsp; 物料编码
                          </>
                        }
                      >
                        <div>{record?.materialNum || '--'}</div>
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-leixing'} />
                            &nbsp; 物料类型
                          </>
                        }
                      >
                        {getColorTextDoms(record?.materialTypeName)}
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-qianming'} />
                            &nbsp; 物料名称
                          </>
                        }
                      >
                        <div style={{ width: '100%' }}>{record?.fullName || '--'}</div>
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-moban'} />
                            &nbsp; 供货分类
                          </>
                        }
                      >
                        {getColorTextDoms(record?.supplyTypeName)}
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-zhuangtai1'} />
                            &nbsp; 物料状态
                          </>
                        }
                      >
                        {/* {stateOfRendering(record?.state, false)} */}
                        {record?.state == 0 ? '起草' : record?.state == 1 ? '审核中' : record?.state == 2 ? '有效' : record?.state == 3 ? '作废' : '--'}
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-tupian'} />
                            &nbsp; 相关图片
                          </>
                        }
                      >
                        {record?.imageInfo ? (
                          <div style={{ width: '100%', height: '20px', overflow: 'hidden' }}>
                            {!isShowEye ? <MyIcon type={'icon-eye'} onClick={handleClickEye} /> : <EyeInvisibleOutlined onClick={handleClickEye} />}
                            {imgArr?.length > 0 ? (
                              <>
                                <Image.PreviewGroup
                                  preview={{
                                    visible: isShowEye,
                                    scaleStep: 0.5,
                                    getContainer: () => document.getElementById('custom-preview-container') as any,
                                    onVisibleChange: (value) => {
                                      setIsShowEye(value);
                                    },
                                  }}
                                >
                                  {imgArr?.map((item, index) => {
                                    return (
                                      <>
                                        <Image style={{ display: 'none' }} src={reqUrl + item} />
                                      </>
                                    );
                                  })}
                                </Image.PreviewGroup>
                              </>
                            ) : (
                              <>
                                <Image
                                  style={{ display: 'none' }}
                                  src={reqUrl + imgArr[0]}
                                  preview={{
                                    visible: isShowEye,
                                    scaleStep: 0.5,
                                    getContainer: () => document.getElementById('custom-preview-container') as any,
                                    onVisibleChange: (value) => {
                                      setIsShowEye(value);
                                    },
                                  }}
                                />
                              </>
                            )}
                          </div>
                        ) : (
                          '--'
                        )}
                      </Descriptions.Item>

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-pinpai'} />
                            &nbsp; 规格型号
                          </>
                        }
                        span={2}
                      >
                        {record?.modelNum || '--'}
                      </Descriptions.Item>

                      {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-fenjie'} />
                            &nbsp; 供货分类
                          </>
                        }
                      >
                        {getColorTextDoms(record?.supplyTypeName)}
                      </Descriptions.Item> */}

                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-guize'} />
                            &nbsp; 规格要求（参数）
                          </>
                        }
                        span={2}
                      >
                        {record?.specInfo || '--'}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-jiage'} />
                            &nbsp; 参考单价（元）
                          </>
                        }
                      >
                        {formatDecimal(record?.unitPrice)}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-celianggongju'} />
                            &nbsp; 量化单位
                          </>
                        }
                      >
                        {getColorTextDoms(record?.unitBusinessName)}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-moban'} />
                            &nbsp; 物料介绍
                          </>
                        }
                        span={2}
                      >
                        {record?.paramsInfo || '--'}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-user'} />
                            &nbsp; 创建人
                          </>
                        }
                      >
                        {record?.createrName || '--'}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-time'} />
                            &nbsp; 创建时间
                          </>
                        }
                      >
                        {record?.createTime ? record?.createTime?.split(' ')?.[0] : '--'}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-gangweitubiao'} />
                            &nbsp; 创建岗位
                          </>
                        }
                      >
                        {record?.createPositionName || '--'}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-bumen'} />
                            &nbsp; 创建部门
                          </>
                        }
                      >
                        {record?.createDepartmentName || '--'}
                      </Descriptions.Item>

                      {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-souhuodizhi'} />
                            &nbsp; 行政区域
                          </>
                        }
                        span={2}
                      >
                        {(record?.provinceName ? record?.provinceName : '') +
                          (record?.cityName ? ` / ${record?.cityName}` : '') +
                          (record?.countyName ? ` / ${record?.countyName}` : '--')}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-souhuodizhi'} />
                            &nbsp; 详细地址
                          </>
                        }
                        span={2}
                      >
                        {record?.addressInfo || '--'}
                      </Descriptions.Item> */}
                    </Descriptions>
                  </div>
                </Panel>
                {/* 审核记录 */}
                <Panel header={<Divider orientation="left">{'审核记录'}</Divider>} key={'material-CollapseCheck'} id={'material-CollapseCheck'}>
                  <div
                    className={prefixCls + 'TimelineStyle'}
                    style={{
                      padding: '25px 0px 0px 10px',
                      textAlign: 'left',
                      margin: '0 10px',
                    }}
                  >
                    {record?.mMaterialChecks?.length >= 1 ? (
                      <>
                        <Timeline>
                          {record?.mMaterialChecks?.map((item: Record<string, any>, index: number, arrs: Record<string, any>[]) => {
                            return (
                              <div key={getKey()}>
                                {item?.checkTime && (
                                  <Timeline.Item dot={<ClockCircleOutlined className="timeline-clock-icon" />} color={'red'}>
                                    <Row
                                      style={{
                                        background: '#f6f6f6',
                                        padding: '5px 10px 10px 10px',
                                        borderRadius: '10px',
                                      }}
                                    >
                                      <Col className={prefixCls + 'TimelineStyle-ColTitle'} span={24}>
                                        {item?.checkTime || '--'} &nbsp;&nbsp;
                                        <span className={prefixCls + 'TimelineStyle-ColState'}>{signStateOfRenderings(Number(item?.checkState))}</span>
                                      </Col>
                                      <Col span={24}>
                                        <MyIcon type="icon-user" />
                                        <span className={prefixCls + 'TimelineStyle-spanLabel'}>审核人：</span>
                                        <span className={prefixCls + 'TimelineStyle-spanWeight'}>{item?.checkerName || '--'}</span>
                                      </Col>
                                      <Col span={24}>
                                        <MyIcon type="icon-bumen" />
                                        <span className={prefixCls + 'TimelineStyle-spanLabel'}>审核部门：</span>
                                        <span className={prefixCls + 'TimelineStyle-spanWeight'}>{item?.checkDepartmentName || '--'}</span>
                                      </Col>
                                      <Col span={24} style={{ display: 'flex' }}>
                                        <MyIcon type="icon-pandian1" />
                                        <span className={prefixCls + 'TimelineStyle-spanLabel'} style={{ whiteSpace: 'nowrap' }}>
                                          审核意见：
                                        </span>
                                        <div className={prefixCls + 'TimelineStyle-spanWeight'}>{item?.checkResult || '--'}</div>
                                      </Col>
                                    </Row>
                                  </Timeline.Item>
                                )}
                                <Timeline.Item dot={<ClockCircleOutlined className="timeline-clock-icon" />}>
                                  <Row
                                    style={{
                                      background: '#f6f6f6',
                                      padding: '5px 10px 10px 10px',
                                      borderRadius: '10px',
                                    }}
                                  >
                                    <Col className={prefixCls + 'TimelineStyle-ColTitle'} span={24}>
                                      {item?.applyTime || '--'} &nbsp;&nbsp;
                                      <span className={prefixCls + 'TimelineStyle-ColState'} style={{ color: '#1677ff' }}>
                                        {index === arrs?.length - 1 ? '提交申请' : '重新提交申请'}
                                      </span>
                                    </Col>
                                    <Col span={24}>
                                      <MyIcon type="icon-user" />
                                      <span className={prefixCls + 'TimelineStyle-spanLabel'}>提交人：</span>
                                      <span className={prefixCls + 'TimelineStyle-spanWeight'}>{item?.applyerName || '--'}</span>
                                    </Col>
                                    <Col span={24}>
                                      <MyIcon type="icon-bumen" />
                                      <span className={prefixCls + 'TimelineStyle-spanLabel'}>提交部门：</span>
                                      <span className={prefixCls + 'TimelineStyle-spanWeight'}>{item?.applyDepartmentName || '--'}</span>
                                    </Col>
                                  </Row>
                                </Timeline.Item>
                              </div>
                            );
                          })}
                        </Timeline>
                      </>
                    ) : (
                      <>
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={'暂无审核记录'} />
                      </>
                    )}
                  </div>
                </Panel>
              </Collapse>
            </Spin>
          </ScrollBarLayout>

          {/* 审核按钮的显示和隐藏 */}
          {record?.state == '1' && record?.signType == '1' && record?.signState == '0' && !isAudit && curRes?.['/materialController/audit'] && (
            <div
              style={{
                padding: '8px 0',
                textAlign: 'center',
                borderTop: '1px dashed #ccc',
              }}
            >
              <Button
                // icon={<FileProtectOutlined />}
                key="submit"
                type="primary"
                loading={false}
                onClick={() => {
                  setIsAudit(true);
                }}
              >
                审核
              </Button>
            </div>
          )}

          {/* 发布和申请按钮的显示和隐藏 【注释：curRes?.['/materialController/publish'] ||】 */}
          {record?.state == '0' && curRes?.['/materialController/applyMaterial'] && (
            <>
              <div
                style={{
                  padding: '8px 0',
                  textAlign: 'center',
                  borderTop: '1px dashed #ccc',
                }}
              >
                {/* {curRes?.['/materialController/publish'] && (
                  <>
                    <Button
                      icon={<SendOutlined />}
                      key="submit"
                      type="primary"
                      loading={false}
                      onClick={() => {
                        setIsShowApplyModal({
                          isShow: true,
                          recordObj: record,
                          type: 'publish',
                          select: 'id',
                        });
                      }}
                    >
                      发布
                    </Button>
                    &nbsp;
                  </>
                )} */}
                {curRes?.['/materialController/applyMaterial'] && (
                  <>
                    &nbsp;
                    <Button
                      // icon={<DeliveredProcedureOutlined />}
                      key="submit"
                      type="primary"
                      loading={false}
                      onClick={() => {
                        setIsShowApplyModal({
                          isShow: true,
                          recordObj: record,
                          type: 'apply',
                          select: 'id',
                        });
                      }}
                    >
                      申请
                    </Button>
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </Drawer>

      <Drawer
        title="审核申请"
        className={prefixCls + 'checkDrawer'}
        style={{
          position: 'absolute',
          overflow: 'hidden',
        }}
        placement={'bottom'}
        onClose={() => {
          setIsAudit(false);
        }}
        open={isAudit}
        key={'buttom'}
        getContainer={() => document.getElementById('oneDetailDrawerBox') as any}
        destroyOnClose={true}
        headerStyle={{ padding: '1rem' }}
        bodyStyle={{ padding: '20px', height: '200px' }}
        closable={false}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Button
              loading={false}
              onClick={() => {
                setIsAudit(false);
              }}
              // icon={<CloseCircleOutlined />}
            >
              取消
            </Button>
            &nbsp;&nbsp;&nbsp;
            <Button
              type="primary"
              loading={false}
              // icon={<CheckCircleOutlined />}
              onClick={() => {
                auditForm?.validateFields()?.then((res) => {
                  auditMaterialRun({
                    ...res,
                    // 一直传第一个是因为后端返回数据的时候做了数据反转 最后一个变成第一个
                    ids: record?.mMaterialChecks?.[0]?.id,
                    versionNum: record?.mMaterialChecks?.[0]?.versionNum,
                  });
                });
              }}
            >
              确定
            </Button>
          </div>
        }
        extra={
          <>
            <CloseOutlined
              onClick={() => {
                setIsAudit(false);
              }}
            />
          </>
        }
      >
        <Spin spinning={auditMaterialLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={auditForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name="checkState"
                    label="审核结果"
                    rules={[
                      {
                        required: true,
                        message: '请选择审核结果',
                      },
                    ]}
                    initialValue={'1'}
                  >
                    <Select
                      placeholder="请选择审核结果"
                      loading={false}
                      onSelect={(val) => {
                        // const checkResult = auditForm?.getFieldValue('checkResult')
                        if (!isChange) {
                          let str = '';
                          if (val == '1') {
                            str = '通过';
                          } else if (val == '2') {
                            str = '退回';
                          } else if (val == '3') {
                            str = '作废';
                          } else {
                            str = '';
                          }
                          auditForm?.setFieldValue('checkResult', str);
                        }
                      }}
                    >
                      <Select.Option value={'1'}>通过</Select.Option>
                      <Select.Option value={'2'}>退回</Select.Option>
                      <Select.Option value={'3'}>作废</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="审核原因"
                    name="checkResult"
                    rules={[
                      {
                        required: true,
                        message: '请填写审核结果',
                      },
                    ]}
                    initialValue={'通过'}
                  >
                    <Input.TextArea
                      placeholder={`请填写审核原因`}
                      showCount
                      maxLength={200}
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      onChange={() => {
                        setIsChange(true);
                      }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </Drawer>

      {/* 发布申请弹窗 */}
      {isShowApplyModal?.isShow && (
        <ApplySignModal
          curRes={curRes}
          onClose={() => {
            setIsShowApplyModal({
              isShow: false,
              recordObj: {},
              type: null,
              select: null,
            });
          }}
          checkRows={isShowApplyModal?.recordObj}
          isShowModal={isShowApplyModal?.isShow}
          reloadManage={() => {
            reloadManage();
            detailMaterialRun({ id: record?.id });
          }}
          modalType={isShowApplyModal?.type}
          isShowIdName={isShowApplyModal?.select}
        />
      )}
    </>
  );
};
export default DetailsDrawer;
